# -*- coding: utf-8 -*-
"""
------------------------------------------------------------------------------
    File Name:  statistics
    Author   :  wanwei1029
    Date     :  2018/10/15
    Desc     : 统计下载信息并图表显示。
------------------------------------------------------------------------------
"""
import sys
sys.path.append("D:\\pycharmProjects\\python_samp")

import time
import redis
import json
import pandas as pd
import matplotlib.pyplot as plt
from sys import argv

import samp.spider.aikantxt.spider_utils as utils

pool = redis.ConnectionPool(host=utils.REDIS_HOST, port=utils.REDIS_PORT, db=utils.REDIS_DB, decode_responses=True)
sr = redis.StrictRedis(connection_pool=pool)


def generate_keys(day):
    keys_list = list()
    i = 0
    while i < 24:
        hour = str(i).zfill(2)
        j = 0
        while j < 6:
            keys_list.append(str(day)+":"+hour+":"+str(j))
            j += 1
        i += 1
    return keys_list


def generate_index_keys():
    keys_list = list()
    i = 0
    while i < 24:
        j = 0
        while j < 6:
            keys_list.append(str(i)+str(j))
            # if j == 0:
            #     keys_list.append(str(i))
            # else:
            #     keys_list.append(str(j))
            j += 1
        i += 1
    return keys_list


def generate_data(day):

    key_lists = generate_keys(day)
    success_list = list()
    error_list = list()
    total_success = 0
    total_error = 0
    for key in key_lists:
        # print("{0}={1}".format(key, get_redis_val(utils.FLAG_SUCCESS+key)))
        # print("{0}={1}".format(key, get_redis_val(utils.FLAG_ERROR+key)))
        success_val = get_redis_val(utils.FLAG_SUCCESS+key)
        success_list.append(success_val)
        error_val = get_redis_val(utils.FLAG_ERROR+key)
        error_list.append(error_val)
        total_success += success_val
        total_error += error_val
    return success_list, error_list, total_success, total_error


def get_redis_val(key):
    value = sr.get(key)
    if value:
        print("{0} download {1}".format(key, value))
        return int(value)
    else:
        return 0


def show_with_plt(day):
    start_date = 15
    current_time = time.localtime()
    current_day = current_time.tm_mday
    success_data = dict()
    error_data = dict()
    total_success_data = dict()
    total_error_data = dict()
    if day:
        success_list, error_list, total_success, total_error = generate_data(day)
        success_data["success_" + str(day)] = success_list
        error_data["error_" + str(day)] = error_list
        print(total_success)
        print(total_error)
        total_success_data[str(day)] = total_success
        total_error_data[str(day)] = total_error
    else:
        while start_date <= current_day:
            success_list, error_list, total_success, total_error = generate_data(start_date)
            success_data["success_" + str(start_date)] = success_list
            error_data["error_" + str(start_date)] = error_list
            print(start_date)
            print(total_success)
            print(total_error)
            total_success_data[str(start_date)] = total_success
            total_error_data[str(start_date)] = total_error
            start_date += 1
    index = generate_index_keys()
    plt.plot(index, success_data["success_20"])
    # plt.scatter(index, success_data["success_20"])
    # plt.xticks(())
    # plt.yticks(())
    plt.show()


def demo(day):
    """
    用pandas，x轴不显示，不知道为啥，win7的可以显示。
    """
    start_date = 15
    current_time = time.localtime()
    current_day = current_time.tm_mday
    success_data = dict()
    error_data = dict()
    total_success_data = dict()
    total_error_data = dict()
    if day:
        success_list, error_list, total_success, total_error = generate_data(day)
        success_data["success_" + str(day)] = success_list
        error_data["error_" + str(day)] = error_list
        print(total_success)
        print(total_error)
        total_success_data[str(day)] = total_success
        total_error_data[str(day)] = total_error
    else:
        while start_date <= current_day:
            success_list, error_list, total_success, total_error = generate_data(start_date)
            success_data["success_"+str(start_date)] = success_list
            error_data["error_"+str(start_date)] = error_list
            print(start_date)
            print(total_success)
            print(total_error)
            total_success_data[str(start_date)] = total_success
            total_error_data[str(start_date)] = total_error
            start_date += 1
    # print(success_data)
    # print(error_data)
    index = generate_keys("")
    # print(index)
    # data = dict(success_data, **error_data)
    # plt.figure(1)
    success_df = pd.DataFrame(success_data, index)
    success_df.plot(title=json.dumps(total_success_data))
    # plt.figure(2)
    error_df = pd.DataFrame(error_data, index)
    error_df.plot(title=json.dumps(total_error_data))
    plt.show()


if __name__ == '__main__':
    test_method = "demo"
    if test_method == "demo":
        day_input = None
        if len(argv) > 1:
            day_input = argv[1]
        demo(day_input)
        # show_with_plt(day_input)
